<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="enterpriseId">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业主键"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="招标标题" prop="bidId">
        <el-input
          v-model="queryParams.bidTitle"
          placeholder="请输入招标主键"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable filterable size="small">
          <el-option
            v-for="dict in bidStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['scm:bidding:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['scm:bidding:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['scm:bidding:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['scm:bidding:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>

    </el-row>

    <el-table v-loading="loading" :data="biddingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <!-- <el-table-column label="主键" align="center" prop="id"/> -->
      <el-table-column label="No." type="index" width="50"></el-table-column>
      <el-table-column label="企业名称" align="center" prop="enterpriseName"></el-table-column>
      <el-table-column label="招标项目" align="center" prop="bidTitle"></el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          {{ getDictValue(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['scm:bidding:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['scm:bidding:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    ></pagination>

    <!-- 添加或修改企业投标对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" label-width="80px">
        <el-form-item label="企业名称" prop="enterpriseId">
          <el-input v-model="form.enterpriseName" readonly placeholder="请输入企业名称"></el-input>
        </el-form-item>
        <el-form-item label="招标标题" prop="bidId">
          <el-input v-model="form.bidTitle" readonly placeholder="请输入招标标题"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态" clearable filterable size="small">
            <el-option
              v-for="dict in bidStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listBidding,
  getBidding,
  delBidding,
  addBidding,
  updateBidding,
  exportBidding
} from '@/api/bid/enterpriseBidding';
// 如有字典接口，可按如下引入（需自行实现）：
// import { getDicts } from '@/api/dict';

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const biddingList = ref([]);
const title = ref('');
const open = ref(false);
const bidStatus = ref([]);

// 查询条件
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  enterpriseName: null,
  bidTitle: null,
  status: null,
});

// 表单数据
const form = reactive({
  id: null,
  enterpriseId: null,
  bidId: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
  status: 0,
});

// 获取 el-form 的引用
const queryForm = ref(null);
const formRef = ref(null);

const getDictValue = (key) => {
  const dict = bidStatus.value.find(x => x.dictValue === key?.toString());
  return dict ? dict.dictLabel : '';
};

const getList = async () => {
  loading.value = true;
  try {
    const response = await listBidding(queryParams);
    biddingList.value = response.rows;
    total.value = response.total;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  // 重置查询表单
  queryForm.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.enterpriseName = null;
  queryParams.bidTitle = null;
  queryParams.status = null;
  getList();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

const resetFormData = () => {
  Object.assign(form, {
    id: null,
    enterpriseId: null,
    bidId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    status: 0,
  });
  formRef.value?.resetFields();
};

const handleAdd = () => {
  resetFormData();
  open.value = true;
  title.value = '添加企业投标';
};

const handleUpdate = async (row) => {
  resetFormData();
  // 如果传入了行数据则使用该数据，否则取选中第一项
  const id = row ? row.id : ids.value[0];
  try {
    const response = await getBidding(id);
    Object.assign(form, response.data);
    open.value = true;
    title.value = '修改企业投标';
  } catch (error) {
    console.error(error);
  }
};

const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      if (form.id != null) {
        await updateBidding(form);
        ElMessage.success('修改成功');
      } else {
        await addBidding(form);
        ElMessage.success('新增成功');
      }
      open.value = false;
      getList();
    }
  });
};

const cancel = () => {
  open.value = false;
  resetFormData();
};

const handleDelete = async (row) => {
  // 如果传入行数据则使用该数据，否则用选中数据
  const deleteIds = row ? row.id : ids.value;
  try {
    await ElMessageBox.confirm(
      `是否确认删除企业投标编号为 "${deleteIds}" 的数据项?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await delBidding(deleteIds);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    console.error(error);
  }
};

const handleExport = async () => {
  try {
    await ElMessageBox.confirm('是否确认导出所有企业投标数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const response = await exportBidding(queryParams);
    // download 为你自定义的下载方法，请根据项目实际实现
    download(response.msg);
  } catch (error) {
    console.error(error);
  }
};

onMounted(async () => {
  getList();
  // 如有字典接口，调用获取字典数据，例如：\n
  // const dictResponse = await getDicts('bid_status');
  // bidStatus.value = dictResponse.data;
});
</script>
